/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       glfoader.cpp
 * Author:     karooolek
 * Created on: 2009-03-24
 *
 **********************************************************************************************************************/

#include "glfloader.h"

namespace mGameEngine
{
namespace Graphics
{

GLFLoader::GLFLoader() : FontLoader()
{
}

GLFLoader::GLFLoader(const String &filename) : FontLoader(filename)
{
}

GLFLoader::~GLFLoader()
{
}

void GLFLoader::load()
{
    // based on glfont2 by Brad Fish
    // http://students.cs.byu.edu/~bfish/glfont2.php

    // begin font loading
    _state = 0.0f;

    // delete old font
    if(_font)
    {
        delete _font;
    }

    // create new font
    _font = new Font();

    // open input file
    FILE *input = fopen(_filename, "rb");
    if(!input)
    {
        return;
    }

    // read header
    GLFHeader header;
    fread((void *)&header, sizeof(header), 1, input);

    // read characters
    for(uint8 c = header.start_char; c != header.end_char + 1; ++c)
    {
        GLFontChar glfch;
        fread((void *)&glfch, sizeof(GLFontChar), 1, input);

        FontCharacter ch;
        ch.position = Vector2(glfch.tx1, glfch.ty2);
        ch.size = Vector2(glfch.tx2, glfch.ty1) - ch.position;

        _font->addCharacter(c, ch);
    }

    // read font pixel data
    uint num_tex_bytes = header.tex_width * header.tex_height * 2;
    uint8 *tex_bytes = new uint8[num_tex_bytes];
    fread((void *)tex_bytes, 1, num_tex_bytes, input);
    for(uint i = 0; i != num_tex_bytes; i += 2)
    {
        tex_bytes[i] = 255;
    }

    // create texture
    Image img(tex_bytes, header.tex_width, header.tex_height, 16);
    _font->setTexture(new Texture(&img));

    // free font pixels data
    delete[] tex_bytes;

    // close input file
    fclose(input);

    // font is loaded
    _state = 1.0f;
}

void GLFLoader::unload()
{
    if(!_font)
    {
        _state = 0.0f;
        return;
    }

    delete _font;

    _state = 0.0f;
}

}
}

